import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

class KeyboardUtil {
  /// 收起键盘
  static void hideKeyboard() {
    FocusScopeNode currentFocus = FocusScope.of(Get.context!);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }
}

class LimitFormatter extends TextInputFormatter {
  final int _scale;

  LimitFormatter(this._scale);

  static const String POINTER = ".";
  static const String TCOLON = ",";
  static const String DOUBLE_ZERO = "00";

  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    String input = newValue.text.replaceAll(TCOLON, POINTER);

    // 不能以小数点开头
    if (input.startsWith(POINTER)) {
      return oldValue;
    }

    // 不能以00开头
    if (input.startsWith(DOUBLE_ZERO)) {
      return oldValue;
    }

    // 只允许数字和一个小数点
    final validNumber = RegExp(r'^\d*\.?\d{0,' + _scale.toString() + r'}$');
    if (!validNumber.hasMatch(input)) {
      return oldValue;
    }

    // 不能有多个小数点
    if (input.split(POINTER).length > 2) {
      return oldValue;
    }

    return TextEditingValue(
      text: input,
      selection: TextSelection.collapsed(offset: input.length),
    );
  }
}

class MaxValueFormatter extends TextInputFormatter {
  final double maxValue;

  MaxValueFormatter(this.maxValue);

  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    // 如果输入为空，直接返回
    if (newValue.text.isEmpty) {
      return newValue;
    }

    // 尝试将输入内容解析为数字
    final double? value = double.tryParse(newValue.text);

    // 如果解析失败或超过最大值，返回旧值
    if (value == null || value > maxValue) {
      return oldValue;
    }
    //去掉前面的0
    if (newValue.text.startsWith("0") && newValue.text.length > 1) {
      return TextEditingValue(text: newValue.text.substring(1), selection: TextSelection.collapsed(offset: newValue.selection.end - 1));
    }
    // 否则，返回新值
    return newValue;
  }
}
